package com.tendory.common.base;

import androidx.annotation.NonNull;
import io.reactivex.Observable;
import io.reactivex.subjects.PublishSubject;

public class RxBus {
    private PublishSubject<Object> bus = PublishSubject.create();

    private static class RxBusHolder {
        private static final RxBus INSTANCE = new RxBus();
    }
    private RxBus() { }
    public static synchronized RxBus getInstance() {
        return RxBusHolder.INSTANCE;
    }

    public void post(@NonNull Object o) {
        if (hasObservers()) {
            bus.onNext(o);
        }
    }

    public Observable<Object> toObserverable() {
        return bus;
    }

    public <T> Observable<T> toObserverable(Class<T> eventType) {
        // ofType = filter + cast
        return bus.ofType(eventType);
    }

    /**
     * 判断是否有订阅者
     */
    public boolean hasObservers() {
        return bus.hasObservers();
    }
}
